﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using AionCxxLibrary.Enums;
using System.Xml;

namespace WorldServer.Data.Templates
{
    [XmlRoot("skill_base_client")]
    public class SkillTemplate : IPostDeserializeAwareTemplate
    {
        static string[] RejectedElements = new string[] { "sfx1", "status_sfx1", "aura_fx", "aura_fx_bone", "aura_fx_slot", "hit_fx_ex2", "hit_fx_ex4", "hit_fx_ex5" };

        [XmlElement("id")]
        public ushort ID;
        [XmlElement("name")]
        public string Name;
        [XmlElement("desc")]
        public string Description;
        [XmlElement("type")]
        public SkillType Type;
        [XmlElement("sub_type")]
        public SkillSubType SubType;
        [XmlElement("skill_category")]
        public string Category;
        [XmlElement("ultra_skill")]
        public byte UltraSkill;
        [XmlElement("ultra_transfer")]
        public byte UltraTransfer;
        [XmlElement("delay_id")]
        public ushort DelayID;
        [XmlElement("activation_attribute")]
        public ActivationAttribute ActivationAttr;
        [XmlElement("cost_charge_weapon")]
        public int ChargeCostWpn;
        [XmlElement("cost_charge_armor")]
        public int ChargeCostArmor;
        [XmlElement("target_slot")]
        public SkillTargetSlot TargetSlot;
        [XmlElement("first_target")]
        public FirstTarget FirstTarget;
        [XmlElement("no_save_on_logout")]
        public string __no_save_on_logout;
        public bool NoSaveOnLogout;
        [XmlElement("delay_time")]
        public int DelayTime;

        [XmlElement("casting_delay")]
        public ushort CastingDelay;

        [XmlAnyElement]
        public List<XmlElement> OtherElements;

        protected override string[] GetRejectedElements()
        {
            return RejectedElements;
        }

        protected override List<XmlElement> GetOtherElements()
        {
            return OtherElements;
        }

        public override void PostDeserialize()
        {
            base.PostDeserialize();
            Name = Normalize(Name);
            Description = Normalize(Description);
            NoSaveOnLogout = __no_save_on_logout == "TRUE";
            __no_save_on_logout = "";

            for (byte i = 0; i < 10; i++)
            {
                IEnumerable<XmlElement> effectElements = OtherElements.Where(elem => elem.Name.StartsWith("effect" + i + "_"));
                if (effectElements.Count() == 2 && effectElements.First().Name == "effect" + i + "_hop_a")
                    continue;
                if (effectElements != null && effectElements.Count() > 0)
                {
                    SkillEffectTemplate effectTemplate = new SkillEffectTemplate();
                    effectTemplate.Order = i;
                    foreach (XmlElement effectEl in effectElements)
                    {
                        string name = effectEl.Name.Replace("effect" + i + "_", "");
                        switch (name)
                        {
                            case "type": try
                                {
                                    effectTemplate.Type = (SkillEffectType)Enum.Parse(typeof(SkillEffectType), effectEl.InnerText, true);
                                }
                                catch (Exception)
                                {
                                    Console.WriteLine("unhandled effect: " + effectEl.InnerText);
                                }
                                break;
                            case "effectid": effectTemplate.EffectID = int.Parse(effectEl.InnerText); break;
                            case "basiclv": effectTemplate.BasicLevel = byte.Parse(effectEl.InnerText); break;
                            case "noresist": if (effectEl.InnerText == "1") effectTemplate.NoResist = true; break;
                            case "target_type": effectTemplate.TargetType = (SkillEffectTargetType)Enum.Parse(typeof(SkillEffectTargetType), effectEl.InnerText, true); break;
                            case "checkforchain": if (effectEl.InnerText == "1") effectTemplate.CheckForChain = true; break;
                            case "cond_preeffect":
                                string pure = effectEl.InnerText.Substring(1);
                                string[] pures = pure.Split('_');
                                foreach (string p in pures)
                                {
                                    effectTemplate.ConditionalPreEffects.Add(byte.Parse(p));
                                }
                                effectTemplate.ConditionalPreEffects.Sort(new Comparison<byte>((b1, b2) =>
                                {
                                    if (b1 == b2)
                                        return 0;
                                    return b1 > b2 ? 1 : -1;
                                }));
                                break;
                            case "cond_preeffect_prob1":
                            case "cond_preeffect_prob2":
                                break;
                            case "hop_type": effectTemplate.HopType = (SkillEffectHopType)Enum.Parse(typeof(SkillEffectHopType), effectEl.InnerText, true); break;
                            case "hop_a": effectTemplate.HopA = int.Parse(effectEl.InnerText); break;
                            case "hop_b": effectTemplate.HopB = int.Parse(effectEl.InnerText); break;
                            case "remain1": effectTemplate.Remain1 = int.Parse(effectEl.InnerText); break;
                            case "remain2": effectTemplate.Remain2 = int.Parse(effectEl.InnerText); break;
                            case "critical_prob_mod2": effectTemplate.CriticalProbabilityMod2 = int.Parse(effectEl.InnerText); break;
                            case "acc_mod1": effectTemplate.AccMod1 = int.Parse(effectEl.InnerText); break;
                            case "acc_mod2": effectTemplate.AccMod2 = int.Parse(effectEl.InnerText); break;
                            case "hidemsg": if (effectEl.Value == "1") effectTemplate.HideMsg = true; break;
                            case "checktime": effectTemplate.CheckTime = int.Parse(effectEl.InnerText); break;
                            case "randomtime": effectTemplate.RandomTime = int.Parse(effectEl.InnerText); break;
                            case "cond_status": effectTemplate.ConditionStatus = (AlteredState)Enum.Parse(typeof(AlteredState), effectEl.InnerText, true); break;
                            case "cond_status_prob1":
                            case "cond_status_prob2":
                                break;
                            case "critical_add_dmg_mod2": effectTemplate.CriticalAddDamageModifier2 = int.Parse(effectEl.InnerText); break;
                            case "cond_attack_dir": effectTemplate.ConditionAttackDir = byte.Parse(effectEl.InnerText); break;
                            case "cond_attack_dir_prob1":
                            case "cond_attack_dir_prob2":
                                break;
                            case "critical_prob_mod1": effectTemplate.CriticalProbabilityMod1 = byte.Parse(effectEl.InnerText); break;
                            case "critical_add_dmg_mod1": effectTemplate.CriticalAddDamageModifier1 = byte.Parse(effectEl.InnerText); break;
                            case "cond_race": effectTemplate.ConditionRace = effectEl.InnerText; break;
                            case "cond_race_prob2":
                            case "cond_race_prob1":
                                break;
                            default:
                                if (name.StartsWith("reserved"))
                                {
                                    byte offset = byte.Parse(name.Substring(name.Length - 1));
                                    object value;
                                    try
                                    {
                                        value = int.Parse(effectEl.InnerText);
                                    }
                                    catch (Exception)
                                    {
                                        value = effectEl.InnerText;
                                    }
                                    effectTemplate.ReservedArgs[offset] = value;
                                }
                                else
                                {
                                    Console.WriteLine("Unhandled Effect " + i + " Info: " + effectEl.Name + " => " + effectEl.InnerText);
                                    Console.ReadLine();
                                }
                                break;

                        }
                    }
                    OtherElements.RemoveAll(elem => elem.Name.StartsWith("effect" + i + "_"));
                }
            }

        }
    }

    public class SkillEffectTemplate
    {
        public byte Order;
        public SkillEffectType Type;
        public int EffectID;
        public byte BasicLevel;
        public object[] ReservedArgs = new object[10];
        public bool NoResist = false;
        public SkillEffectTargetType TargetType;
        public bool CheckForChain = false;
        public List<byte> ConditionalPreEffects = new List<byte>();
        public SkillEffectHopType HopType;
        public int HopA;
        public int HopB;
        public int Remain1;
        public int Remain2;
        public int CriticalProbabilityMod2;
        public int AccMod1;
        public int AccMod2;
        public bool HideMsg = false;
        public int CheckTime;
        public int RandomTime;
        public AlteredState ConditionStatus;
        public int CriticalAddDamageModifier1;
        public int CriticalAddDamageModifier2;
        public int CriticalProbabilityMod1;
        public byte ConditionAttackDir;
        public string ConditionRace;
    }

    public class SkillLearnTemplate : IPostDeserializeAwareTemplate
    {
        static string[] RejectedElements = new string[] { };

        [XmlElement("id")]
        public int ID;
        [XmlElement("name")]
        public string Name;
        [XmlElement("race")]
        public string Race;
        [XmlElement("class")]
        public CharacterClass Class;
        [XmlElement("pc_level")]
        public byte CharLevel;
        [XmlElement("skill")]
        public string SkillName;
        [XmlElement("skill_level")]
        public byte SkillLevel;
        [XmlElement("autolearn")]
        public string __AutoLearn;

        public bool AutoLearn;

        public List<XmlElement> OtherElements = new List<XmlElement>();

        protected override string[] GetRejectedElements()
        {
            return RejectedElements;
        }

        protected override List<XmlElement> GetOtherElements()
        {
            return OtherElements;
        }
        public override void PostDeserialize()
        {
            base.PostDeserialize();
            Name = Normalize(Name);
            Race = Normalize(Race);
            SkillName = Normalize(SkillName);
            AutoLearn = __AutoLearn == "TRUE";
        }
    }

}
